package tlog

import (
	"context"
	"go.uber.org/zap/zapcore"
)

type logKey struct{}

type logVal struct {
	fields []zapcore.Field
}

// LogStart start a session log, the input fields here will be printed
// and appended to the session (shared fields)
func LogStart(ctx context.Context, fields ...zapcore.Field) context.Context {
	slog, ok := ctx.Value(logKey{}).(*logVal)
	if ok {
		if len(fields) > 0 {
			slog.fields = append(slog.fields, fields...)
		}
	} else {
		slog = &logVal{make([]zapcore.Field, 0)}
		if len(fields) > 0 {
			slog.fields = append(slog.fields, fields...)
		}
		ctx = context.WithValue(ctx, logKey{}, slog)
	}
	return ctx
}

// LogAppend append a session log (not concurrent safe),
// if no LogStart is called before, the input fields will be discarded
func LogAppend(ctx context.Context, fields ...zapcore.Field) {
	slog, ok := ctx.Value(logKey{}).(*logVal)
	if ok {
		if len(fields) > 0 {
			slog.fields = append(slog.fields, fields...)
		}
	} else {
		// should start first
	}
}

// LogFlush flush a session log, the input fields here will be printed,
// but not appended to the session (private fields)
func LogFlush(ctx context.Context, mkey string, fields ...zapcore.Field) {
	slog, ok := ctx.Value(logKey{}).(*logVal)
	if ok {
		if len(slog.fields) > 0 {
			fields = append(slog.fields, fields...)
		}
	}
	defaultLog.writelog(ctx, "info", mkey, fields...)
}
